// pages/inspection/profile/profile.ts
import api from '../../../api/index';
import common from '../../../common/index';
import { FollowInfoType, CollectionItemType } from '../../../types';

Page({
    data: {
        statusBarHeight: 0,
        navBarHeight: 0,
        userInfo: null as any,
        activeTab: 'collections',
        showSearchBox: false,
        searchKeyword: '',
        collections: [] as CollectionItemType[],
        filteredCollections: [] as CollectionItemType[],
        likes: [] as CollectionItemType[],
        filteredLikes: [] as CollectionItemType[],
        isEditing: false,
        showPostsSearchBox: false,
        postsSearchKeyword: '',
        posts: [],
        postsPageIndex: 1,
        postsPageSize: 10,
        postsHasMore: true,
        filteredPosts: [] as any[],
        pcenterPageShow: false,
        isViewingOtherUser: false,
        showToast: false,
        isCollecting: false,
        showTagModal: false,
        availableTags: [] as {name: string, selected: boolean}[],
        selectedTags: [] as string[],
        newTagName: '',
        showRenameModal: false,
        renameTagName: '',
        renameNewName: '',
        isTagsExpanded: false,
        showTagActionSheet: false,
        showTagSettingsMenu: false,
        currentItem: null
    },

    // 头像加载成功回调
    onAvatarLoad(e: any) {
        console.log('头像加载成功');
    },

    // 头像加载失败回调
    onAvatarError(e: any) {
        const type = e.currentTarget.dataset.type;
        console.log('头像加载失败，使用默认头像');
        
        if (type === 'user') {
            this.setDefaultAvatar();
        }
    },

    // 测试方法：验证页面是否能正常打开
    testPageLoad() {
        // 页面加载成功
    },

    onLoad(options: any) {
        try {
            const app = getApp();
            
            const targetUid = options?.uid;
            const targetUsername = options?.username;
            
            if (targetUid && targetUid !== '') {
                // 查看其他用户
                const targetUserInfo = {
                    uid: targetUid,
                    nickName: targetUsername || '用户',
                    nickname: targetUsername || '用户',
                    following: 0,
                    followers: 0,
                    icon: '/assets/image/def-icon.png'
                };
                
                this.setData({ 
                    statusBarHeight: app.globalData.statusBarHeight,
                    navBarHeight: app.globalData.navBarHeight,
                    userInfo: targetUserInfo,
                    isViewingOtherUser: true
                });
                
                this.fetchTargetUserInfo(targetUid);
                this.fetchTargetUserFollowInfo(targetUid);
                this.fetchTargetUserCollections(targetUid);
                
            } else {
                // 查看自己的profile
                const userInfo = common.getAppUserInfo();
                
                // 直接使用本地用户信息，不立即设置默认头像
                const userInfoWithStats = {
                    ...userInfo,
                    following: userInfo ? (userInfo.following || 0) : 0,
                    followers: userInfo ? (userInfo.followers || 0) : 0
                    // 不设置icon，让fetchUserInfo处理
                };
                
                this.setData({ 
                    statusBarHeight: app.globalData.statusBarHeight,
                    navBarHeight: app.globalData.navBarHeight,
                    userInfo: userInfoWithStats,
                    isViewingOtherUser: false
                });
                
                this.fetchUserInfo();
                this.fetchFollowInfo();
                this.fetchCollections();
                this.fetchAvailableTags();
            }
        } catch (error: any) {
            const app = getApp();
            const defaultUserInfo = {
                uid: '',
                nickName: '用户',
                nickname: '用户',
                following: 0,
                followers: 0,
                icon: '/assets/image/def-icon.png'
            };
            
            this.setData({ 
                statusBarHeight: app.globalData.statusBarHeight,
                navBarHeight: app.globalData.navBarHeight,
                userInfo: defaultUserInfo,
                isViewingOtherUser: false
            });
        }
    },


    // 获取用户基本信息
    async fetchUserInfo() {
        try {
            const user = common.getAppUserInfo();
            const uid = user.uid || user.userId || '';
            
            if (!uid) {
                return;
            }
            
            const requestData = { uid };
            const res = await api.getUserInfo(requestData);
            
            if (res) {
                // 采用inspection页面的简单处理方式
                let iconField = (res as any).icon || (res as any).avatar || (res as any).avatarUrl || '';
                
                // 如果接口没有返回头像信息，尝试从本地存储获取
                if (!iconField) {
                    const localUser = common.getLocalUser();
                    const appUser = common.getAppUserInfo();
                    iconField = localUser.icon || appUser.icon || '';
                }
                
                // 采用inspection页面的头像URL处理逻辑
                if (iconField && !iconField.startsWith('http')) {
                    // 与inspection页面相同的处理逻辑
                    iconField = 'https://www.aispire.info' + iconField.replace(/.*?(?=\/user_portrait)/, '');
                    console.log('采用inspection页面方式处理后的头像URL:', iconField);
                }
                
                // 更新用户信息显示
                this.updateUserInfoDisplay({
                    ...res,
                    icon: iconField
                });
            }
        } catch (error: any) {
            console.error('获取用户信息失败:', error);
        }
    },

    

    setDefaultAvatar() {
        const currentUserInfo = this.data.userInfo;
        if (currentUserInfo) {
            const updatedUserInfo = {
                ...currentUserInfo,
                icon: '/assets/image/def-icon.png'
            };
            this.setData({ userInfo: updatedUserInfo });
            
            // wx.showToast({
            //     title: '头像加载失败，已使用默认头像',
            //     icon: 'none',
            //     duration: 2000
            // });
        }
    },

    // 在processAvatarUrl方法中添加签名修复
    processAvatarUrl(iconField: string): string {
        if (!iconField) {
          return '/assets/image/def-icon.png';
        }
        
        console.log('原始头像URL:', iconField);
        
        // 如果是默认头像，直接返回
        if (iconField.includes('def-icon.png')) {
          return iconField;
        }
        
        let processedUrl = iconField;
        
        // 处理OSS URL
        if (iconField.includes('oss-cn-hangzhou.aliyuncs.com')) {
          processedUrl = this.fixOssUrlEncoding(iconField);
        }
        // 处理相对路径
        else if (iconField.startsWith('/') && !iconField.startsWith('http')) {
          processedUrl = 'https://www.aispire.info' + this.decodeUrlPath(iconField);
        }
        // 处理其他编码URL
        else if (iconField.includes('%2F')) {
          processedUrl = this.decodeUrlPath(iconField);
        }
        
        console.log('处理后的头像URL:', processedUrl);
        return processedUrl;
      },
  
  // 修复OSS URL
  fixOssUrlEncoding(url: string): string {
    // 解码路径部分
    let fixedUrl = url.replace(/%2F/g, '/');
    
    // 修复签名参数（保持其他参数不变）
    // OSS签名需要特定的编码格式，这里只修复路径部分
    console.log('OSS URL修复完成:', fixedUrl);
    return fixedUrl;
  },
  decodeUrlPath(url: string): string {
    return url.replace(/%2F/g, '/').replace(/%2B/g, '+').replace(/%3D/g, '=');
  },

      isValidAvatarUrl(url: string): boolean {
        if (!url) return false;
        
        // 如果是默认头像，认为有效
        if (url.includes('def-icon.png')) return true;
        
        // 检查是否是完整的HTTP URL
        if (url.startsWith('http://') || url.startsWith('https://')) {
          return true;
        }
        
        // 检查是否是有效的本地路径
        if (url.startsWith('/') && !url.includes('%2F')) {
          return true;
        }
        
        console.log('无效的头像URL:', url);
        return false;
      },

    // 统一更新用户信息显示
    updateUserInfoDisplay(userInfo: any) {
        if (!userInfo) return;
        
        // 采用inspection页面的简单处理逻辑
        const currentUserInfo = this.data.userInfo || {};
        
        // 简单合并，直接使用新数据的头像
        let finalIcon = userInfo.icon || currentUserInfo.icon || '';
        
        // 如果新数据是相对路径，但当前数据是完整URL，保持当前数据
        if (userInfo.icon && !userInfo.icon.startsWith('http') && currentUserInfo.icon && currentUserInfo.icon.startsWith('http')) {
            finalIcon = currentUserInfo.icon;
        }
        
        const updatedUserInfo = {
            ...currentUserInfo,
            ...userInfo,
            icon: finalIcon
        };
        
        this.setData({
            userInfo: updatedUserInfo,
        });
        
        console.log('用户信息更新完成，头像URL:', finalIcon);
    },


    // 获取用户关注信息
    async fetchFollowInfo() {
        try {
            // 获取用户uid
            const user = common.getAppUserInfo();
            const uid = user.uid || user.userId || '';
            
            if (!uid) {
                return;
            }
            
            const requestData = { uid };
            const res = await api.getFollowInfo(requestData);
            
            if (res) {
                // 专门更新关注信息，不通过updateUserInfoDisplay方法
                const followData = {
                    following: res.following_count || res.following || 0,
                    followers: res.follower_count || res.followers || 0
                };
                
                // 直接更新用户信息中的关注数据
                const currentUserInfo = this.data.userInfo || {};
                const updatedUserInfo = {
                    ...currentUserInfo,
                    following: followData.following,
                    followers: followData.followers
                };
                
                this.setData({ userInfo: updatedUserInfo });
            } else {
                wx.showToast({
                    title: '获取关注信息失败',
                    icon: 'error'
                });
            }
        } catch (error: any) {
            wx.showToast({
                title: '网络错误',
                icon: 'error'
            });
        }
    },

    // 获取用户点赞列表
    async fetchLikesList() {
        try {
            console.log('=== 获取用户点赞列表 ===');
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            if (!uid) {
                console.error('用户uid不存在，无法获取点赞列表');
                return;
            }
            
            console.log('请求参数:', { uid });
            
            const res = await api.inspirationLikeList({ uid });
            console.log('点赞列表接口返回:', res);
            
            if (res.data && Array.isArray(res.data)) {
                console.log('点赞列表数据:', res.data);
                
                // 转换数据格式
                const likes = res.data.map(item => ({
                    id: item.id || item.inspiration_id || '',
                    uid: item.uid || '',
                    title: item.title || item.ai_title || '点赞内容',
                    ai_title: item.ai_title,
                    content: item.content,
                    citation: item.citation,
                    link: item.link,
                    image_url: item.image_url || item.image || '../../assets/image/1.png',
                    collection: item.collection || 0,
                    like: item.like || 0,
                    username: item.nickname || item.username || item.uid || '用户',
                    avatar: item.icon || item.avatar || '../../assets/image/1.png',
                    tags: item.tag || item.tags || [],
                    publish_time: item.publish_time,
                    createTime: item.create_time || item.publish_time || '2023-10-18',
                    collected: item.collected || false // 点赞内容的收藏状态
                }));
                
                console.log('转换后的点赞列表:', likes);
                
                this.setData({ 
                    likes,
                    filteredLikes: likes
                });
                
                console.log('点赞列表设置完成');
            } else {
                console.log('点赞列表为空或格式错误');
                this.setData({ 
                    likes: [],
                    filteredLikes: []
                });
            }
        } catch (error: any) {
            console.error('获取点赞列表失败:', error);
            this.setData({ 
                likes: [],
                filteredLikes: []
            });
        }
    },

    // 获取用户收藏列表
    async fetchCollections() {
        try {
            console.log('=== 获取用户收藏列表 ===');
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            if (!uid) {
                console.error('用户uid不存在，无法获取收藏列表');
                return;
            }
            
            console.log('请求参数:', { uid });
            
            const res = await api.getCollectionList({ uid, pageIndex: 1, pageSize: 20 });
            console.log('收藏列表接口返回:', res);
            
            if (res.data && Array.isArray(res.data)) {
                console.log('收藏列表数据:', res.data);
                
                // 转换数据格式
                const collections = res.data.map(item => ({
                    id: item.id || item.inspiration_id || '',
                    uid: item.uid || '',
                    title: item.title || item.ai_title || '收藏内容',
                    ai_title: item.ai_title,
                    content: item.content,
                    citation: item.citation,
                    link: item.link,
                    image_url: item.image_url || item.image || '../../assets/image/1.png',
                    collection: item.collection || 0,
                    like: item.like || 0,
                    username: item.nickname || item.username || item.uid || '用户',
                    avatar: item.icon || item.avatar || '../../assets/image/1.png',
                    tags: item.tag || item.tags || [],
                    publish_time: item.publish_time,
                    createTime: item.create_time || item.publish_time || '2023-10-18',
                    collected: true // 收藏列表中的内容都是已收藏状态
                }));
                
                console.log('转换后的收藏列表:', collections);
                
                this.setData({
                    collections: collections,
                    filteredCollections: collections
                });
                
                console.log('收藏列表设置完成');
            } else {
                console.log('收藏列表为空');
                this.setData({
                    collections: [],
                    filteredCollections: []
                });
            }
        } catch (error) {
            console.error('获取收藏列表失败:', error);
            this.setData({
                collections: [],
                filteredCollections: []
            });
        }
    },

    // 获取用户发布列表
    async fetchPublishedList(isLoadMore: boolean = false) {
        try {
            console.log('=== 获取用户发布列表 ===');
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            if (!uid) {
                console.error('用户uid不存在，无法获取发布列表');
                return;
            }
            
            // 如果是加载更多，增加页码；否则重置为第一页
            const pageIndex = isLoadMore ? this.data.postsPageIndex + 1 : 1;
            const pageSize = this.data.postsPageSize;
            
            console.log('请求参数:', { uid, page_index: pageIndex, page_size: pageSize });
            
            const res = await api.getPublishedList({ uid, page_index: pageIndex, page_size: pageSize });
            console.log('发布列表接口返回:', res);
            
            if (res?.data && Array.isArray(res?.data)) {
                console.log('发布列表数据:', res.data);
                
                // 转换数据格式
                const newPosts = res?.data?.map(item => ({
                    id: item.id || item.inspiration_id || '',
                    uid: item.uid || '',
                    title: item.title || item.ai_title || '发布内容',
                    ai_title: item.ai_title,
                    content: item.content,
                    citation: item.citation,
                    link: item.link,
                    image_url: item.image_url || item.image || '../../assets/image/1.png',
                    collection: item.collect_count || item.collection || 0,
                    like: item.like_count || item.like || 0,
                    comments: item.comment_count || item.comments || 0,
                    username: item.nickname || item.username || item.uid || '用户',
                    avatar: item.icon || item.avatar || '../../assets/image/1.png',
                    tags: item.tag || item.tags || [],
                    publish_time: item.publish_time,
                    createTime: item.create_time || item.publish_time || '2023-10-18',
                    checked: false,
                    collected: item.collected || false // 发布内容的收藏状态
                }));
                
                console.log('转换后的发布列表:', newPosts);
                
                // 更新数据
                if (isLoadMore) {
                    // 加载更多：追加数据
                    const allPosts = [...this.data.posts, ...newPosts];
                    this.setData({ 
                        posts: allPosts,
                        postsPageIndex: pageIndex,
                        postsHasMore: newPosts.length === pageSize
                    });
                } else {
                    // 首次加载：替换数据
                    this.setData({ 
                        posts: newPosts,
                        postsPageIndex: 1,
                        postsHasMore: newPosts.length === pageSize
                    });
                }
                
                // 更新筛选后的数据
                this.filterPosts();
                
                console.log('发布列表设置完成');
                console.log('posts数据:', this.data.posts);
                console.log('filteredPosts数据:', this.data.filteredPosts);
                console.log('filteredPosts长度:', this.data.filteredPosts.length);
            } else {
                console.log('发布列表为空或格式错误');
                if (!isLoadMore) {
                    this.setData({ 
                        posts: [],
                        postsPageIndex: 1,
                        postsHasMore: false
                    });
                    this.filterPosts();
                }
            }
        } catch (error: any) {
            console.error('获取发布列表失败:', error);
            if (!isLoadMore) {
                this.setData({ 
                    posts: [],
                    postsPageIndex: 1,
                    postsHasMore: false
                });
                this.filterPosts();
            }
        }
    },

    // 获取目标用户基本信息
    async fetchTargetUserInfo(uid: string) {
        try {
            console.log('=== 获取目标用户基本信息 ===');
            
            const res = await api.getUserInfo({ uid });
            console.log('目标用户信息接口返回:', res);
            
            if (res) {
                // 采用inspection页面的处理方式
                let iconField = res.icon || res.avatar || res.avatarUrl || '';
                
                // 处理头像URL
                if (iconField && !iconField.startsWith('http')) {
                    iconField = 'https://www.aispire.info' + iconField.replace(/.*?(?=\/user_portrait)/, '');
                    console.log('目标用户头像URL处理:', iconField);
                }
                
                const targetUserInfo = {
                    ...this.data.userInfo,
                    ...res,
                    icon: iconField,
                    uid: uid
                };
                
                this.setData({ userInfo: targetUserInfo });
                console.log('目标用户信息设置完成');
            }
        } catch (error: any) {
            console.error('获取目标用户信息失败:', error);
        }
    },

    // 获取目标用户关注信息
    async fetchTargetUserFollowInfo(uid: string) {
        try {
            console.log('=== 获取目标用户关注信息 ===');
            console.log('目标用户uid:', uid);
            
            const res = await api.getFollowInfo({ uid });
            console.log('目标用户关注信息接口返回:', res);
            
            if (res) {
                console.log('目标用户关注信息:', res);
                console.log('关注数:', res.following_count || res.following || 0);
                console.log('粉丝数:', res.follower_count || res.followers || 0);
                
                const currentUserInfo = this.data.userInfo;
                const updatedUserInfo = {
                    ...currentUserInfo,
                    following: res.following_count || res.following || 0,
                    followers: res.follower_count || res.followers || 0
                };
                
                console.log('更新后的目标用户信息:', updatedUserInfo);
                this.setData({ userInfo: updatedUserInfo });
                console.log('目标用户关注信息设置完成');
            }
        } catch (error: any) {
            console.error('获取目标用户关注信息失败:', error);
        }
    },

    // 获取目标用户收藏列表
    async fetchTargetUserCollections(uid: string) {
        try {
            console.log('=== 获取目标用户收藏列表 ===');
            console.log('目标用户uid:', uid);
            
            const res = await api.getCollectionList({ uid, pageIndex: 1, pageSize: 20 });
            console.log('目标用户收藏列表接口返回:', res);
            
            if (res.data && Array.isArray(res.data)) {
                console.log('目标用户收藏列表数据:', res.data);
                
                // 转换数据格式
                const collections = res.data.map(item => ({
                    id: item.id || item.inspiration_id || '',
                    uid: item.uid || '',
                    title: item.title || item.ai_title || '收藏内容',
                    ai_title: item.ai_title,
                    content: item.content,
                    citation: item.citation,
                    link: item.link,
                    image_url: item.image_url || item.image || '../../assets/image/1.png',
                    collection: item.collection || 0,
                    like: item.like || 0,
                    username: item.nickname || item.username || item.uid || '用户',
                    avatar: item.icon || item.avatar || '../../assets/image/1.png',
                    tags: item.tag || item.tags || [],
                    publish_time: item.publish_time,
                    createTime: item.create_time || item.publish_time || '2023-10-18'
                }));
                
                console.log('转换后的目标用户收藏列表:', collections);
                
                this.setData({ 
                    collections,
                    filteredCollections: collections
                });
                
                console.log('目标用户收藏列表设置完成');
            } else {
                console.log('目标用户收藏列表为空或格式错误');
                this.setData({ 
                    collections: [],
                    filteredCollections: []
                });
            }
        } catch (error: any) {
            console.error('获取目标用户收藏列表失败:', error);
            this.setData({ 
                collections: [],
                filteredCollections: []
            });
        }
    },

    // 获取用户昵称首字母
    getFirstLetter(nickname: string): string {
        if (!nickname || nickname.length === 0) {
            return 'A';
        }
        
        const firstChar = nickname.charAt(0).toUpperCase();
        if (/[\u4e00-\u9fa5]/.test(firstChar)) {
            return firstChar;
        }
        if (/[a-zA-Z]/.test(firstChar)) {
            return firstChar;
        }
        return 'A';
    },

    // 验证头像URL是否有效
    isValidAvatarUrl(url: string): boolean {
        if (!url) return false;
        
        // 如果是默认头像，认为有效
        if (url.includes('def-icon.png')) return true;
        
        // 检查是否是有效的HTTP URL
        if (!url.startsWith('http')) return false;
        
        // 检查是否包含过期或签名参数（可能已过期）
        if (url.includes('Expires=') || url.includes('Signature=')) {
            // 可以进一步检查过期时间，这里简单返回false
            return false;
        }
        
        return true;
    },

    onShow() {
        // 获取最新的用户信息
        const userInfo = common.getAppUserInfo();
        
        if (userInfo) {
            const currentUserInfo = this.data.userInfo;
            
            if (!currentUserInfo || !currentUserInfo.uid || currentUserInfo.uid !== (userInfo?.uid || userInfo?.userId)) {
                const userInfoWithStats = {
                    ...userInfo,
                    following: userInfo.following || 0,
                    followers: userInfo.followers || 0
                };
                
                this.setData({
                    userInfo: userInfoWithStats,
                });
            } else {
                // 如果当前用户信息没有头像，但新获取的用户信息有头像，则更新头像
                if (!currentUserInfo.icon && userInfo.icon) {
                    const updatedUserInfo = {
                        ...currentUserInfo,
                        icon: userInfo.icon
                    };
                    this.setData({ userInfo: updatedUserInfo });
                }
            }
        }
        
        if (!this.data.userInfo || !this.data.userInfo.icon) {
            this.fetchUserInfo();
        }
        
        // 刷新当前tab的数据
        if (this.data.activeTab === 'collections') {
            this.fetchCollections();
        } else if (this.data.activeTab === 'posts') {
            this.fetchPublishedList();
        } else if (this.data.activeTab === 'likes') {
            this.fetchLikesList();
        }
    },

    goBack: function() {
        wx.navigateBack({
            delta: 1  // 返回上一页
        });
    },

    // 显示个人中心页面
    showPcenterPage() {
        this.setData({
            pcenterPageShow: true
        });
    },

    // 关闭个人中心页面
    closePcenterPage() {
        this.setData({
            pcenterPageShow: false
        });
    },

    switchTab(e: any) {
        const tab = e.currentTarget.dataset.tab;
        
        // 清空已选标签
        const availableTags = this.data.availableTags.map(tag => ({
            ...tag,
            selected: false
        }));
        
        this.setData({
            activeTab: tab,
            availableTags: availableTags,
            selectedTags: []
        });
        
        // 如果切换到发布tab，获取发布列表数据
        if (tab === 'posts') {
            console.log('切换到发布tab，开始获取发布列表');
            this.fetchPublishedList();
        }
        // 如果切换到点赞tab，获取点赞列表数据
        else if (tab === 'likes') {
            console.log('切换到点赞tab，开始获取点赞列表');
            this.fetchLikesList();
        }
        // 如果切换到收藏tab，获取收藏列表数据
        else if (tab === 'collections') {
            console.log('切换到收藏tab，开始获取收藏列表');
            this.fetchCollections();
        }
    },

    // 搜索功能已隐藏：保持列表为完整集合
    toggleSearch: function() { /* no-op */ },
    onSearchInput: function(_e) { /* no-op */ },
    clearSearch: function() { /* no-op */ },
    filterCollections: function() {
        this.setData({ filteredCollections: this.data.collections });
    },

    // 切换编辑模式
    toggleEditMode: function() {
        const isEditing = !this.data.isEditing;
        // 退出编辑模式时清除选中状态
        const posts = this.data.posts.map(item => {
            return {...item, checked: false};
        });
        this.setData({
            isEditing,
            posts,
            filteredPosts: this.filterPosts(posts, this.data.postsSearchKeyword)
        });
    },

    // 复选框变化事件
    onCheckboxChange: function(e) {
        const id = e.currentTarget.dataset.id;
        const posts = this.data.posts.map(item => {
            if (item.id === id) {
                return {...item, checked: !item.checked};
            }
            return item;
        });
        this.setData({
            posts,
            filteredPosts: this.filterPosts(posts, this.data.postsSearchKeyword)
        });
    },

    deleteSelectedPosts: function() {
        const selectedIds = this.data.posts
          .filter(item => item.checked)
          .map(item => item.id);
        
        if (selectedIds.length === 0) {
          wx.showToast({
            title: '请先选择要删除的内容',
            icon: 'none'
          });
          return;
        }
        
        wx.showModal({
          title: '确认删除',
          content: `确定要删除选中的${selectedIds.length}条内容吗？`,
          success: (res) => {
            if (res.confirm) {
              // 过滤掉被选中的posts
              const remainingPosts = this.data.posts.filter(item => !item.checked);
              
              this.setData({
                posts: remainingPosts,
                filteredPosts: this.filterPosts(remainingPosts, this.data.postsSearchKeyword),
                isEditing: false
              });
              
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 1500
              });
              
              // 模拟删除后的数据变化效果
              setTimeout(() => {
                if (remainingPosts.length === 0) {
                  this.setData({
                    showEmptyTip: true
                  });
                }
              }, 1500);
            }
          }
        });
      },

    // 筛选发布内容
    filterPosts: function(posts = this.data.posts, keyword = this.data.postsSearchKeyword) {
        let filtered = posts;
        if (keyword) {
          const searchKey = keyword.toLowerCase();
          filtered = posts.filter(item => 
            item.title && item.title.toLowerCase().includes(searchKey)
          );
        }
        
        // 更新筛选后的数据
        this.setData({
            filteredPosts: filtered
        });
        
        return filtered;
    },

    // 搜索功能已隐藏：发布列表不支持搜索
    togglePostsSearch: function() { /* no-op */ },
    onPostsSearchInput: function(_e) { /* no-op */ },
    clearPostsSearch: function() { /* no-op */ },

    // 显示删除确认对话框
    showDeleteConfirm: function(e) {
        const id = e.currentTarget.dataset.id;
        wx.showModal({
            title: '确认删除',
            content: '确认删除该发布吗？',
            success: (res) => {
                if (res.confirm) {
                    this.deletePost(id);
                }
            }
        });
    },

    // 删除单条内容
    async deletePost(id: string) {
        try {
            console.log('=== 开始删除发布内容 ===');
            console.log('删除内容ID:', id);
            
            // 获取用户uid
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            if (!uid) {
                console.error('用户uid不存在，无法删除内容');
                wx.showToast({
                    title: '用户信息错误',
                    icon: 'error'
                });
                return;
            }
            
            const requestData = { uid, id };
            console.log('删除接口请求参数:', requestData);
            
            // 调用删除接口
            const res = await api.deleteInspiration(requestData);
            console.log('删除接口返回:', res);
            
            if (res && res.status === 'success') {
                // 删除成功，从本地数据中移除
                const posts = this.data.posts.filter(item => item.id !== id);
                this.setData({
                    posts,
                    filteredPosts: this.filterPosts(posts, this.data.postsSearchKeyword)
                });
                
                wx.showToast({
                    title: '删除成功',
                    icon: 'success'
                });
                
                console.log('删除成功，本地数据已更新');
            } else {
                // 删除失败
                const errorMsg = res?.message || '删除失败';
                console.error('删除失败:', errorMsg);
                wx.showToast({
                    title: errorMsg,
                    icon: 'error'
                });
            }
        } catch (error: any) {
            console.error('删除操作异常:', error);
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'error'
            });
        }
    },
    
    navigateToFollowList: function(e) {
        const initialTab = e.currentTarget.dataset.type; // 'following'或'followers'
        wx.navigateTo({
          url: `/pages/inspection/followList/followList?initialTab=${initialTab}`
        });
      },

    // 收藏卡片点击事件
    onCollectionCardClick(e: any) {
        const item = e.currentTarget.dataset.item;
        console.log('点击收藏卡片:', item);
        
        if (item && item.id) {
            // 跳转到详情页面
            wx.navigateTo({
                url: `/pages/inspection/detail/detail?id=${item.id}&uid=${item.uid}&author_id=${item.username}`
            });
        } else {
            wx.showToast({
                title: '数据错误',
                icon: 'error'
            });
        }
    },

    // 收藏/取消收藏方法
    async onCollectionClick(e: any) {
        const { id, type } = e.currentTarget.dataset;
        console.log('点击收藏图标:', { id, type });
        
        // 防重复点击检查
        if (this.data.isCollecting) {
            console.log('收藏操作正在进行中，忽略重复点击');
            return;
        }
        
        // 根据类型确定数据源
        let dataSource: any[] = [];
        let dataKey = '';
        
        if (type === 'collection') {
            dataSource = [...this.data.collections];
            dataKey = 'collections';
        } else if (type === 'post') {
            dataSource = [...this.data.posts];
            dataKey = 'posts';
        }
        
        if (dataSource.length === 0) {
            console.error('数据源为空');
            return;
        }
        
        // 找到对应的数据项
        const index = dataSource.findIndex(item => item.id === id);
        
        if (index !== -1) {
            const item = dataSource[index];
            const isCollected = item.collected || false;
            const action = isCollected ? 'cancel' : 'collect';
            
            // 设置收藏操作状态，防止重复点击
            this.setData({ isCollecting: true });
            
            try {
                console.log('=== 调用收藏接口 ===');
                console.log('请求参数:', { 
                    uid: this.data.userInfo.uid, 
                    id: item.id, 
                    action 
                });
                
                // 调用toggleCollection接口
                const res = await api.toggleCollection({
                    uid: this.data.userInfo.uid,
                    id: item.id,
                    action
                });
                
                console.log('收藏接口返回:', res);
                
                // 使用类型断言处理接口返回的数据结构
                const resData = res as any;
                
                if (resData.status === 'success') {
                    // 显示操作成功提示
                    wx.showToast({
                        title: !isCollected ? '已收藏' : '已取消收藏',
                        icon: 'success'
                    });
                    
                    // 收藏操作成功后，调用接口刷新数据，确保数据一致性
                    console.log('收藏操作成功，开始刷新数据...');
                    
                    if (type === 'collection') {
                        // 刷新收藏列表
                        await this.fetchCollections();
                    } else if (type === 'post') {
                        // 刷新发布列表
                        await this.fetchPublishedList();
                    }
                    
                    console.log('数据刷新完成');
                } else {
                    wx.showToast({
                        title: resData.message || '操作失败',
                        icon: 'error'
                    });
                }
            } catch (error: any) {
                console.error('收藏操作失败:', error);
                wx.showToast({
                    title: '网络错误，请重试',
                    icon: 'error'
                });
            } finally {
                // 无论成功失败，都要重置收藏操作状态
                this.setData({ isCollecting: false });
            }
        }
    },

    // 隐藏提示框
    hideToast() {
        this.setData({ showToast: false });
    },

    // 空操作，防止事件冒泡
    noop() {
        // 空函数，用于阻止事件冒泡
    },

    navigateToPublish() {
        wx.navigateTo({
            url: '/pages/inspection/publish/publish'
        });
    },

    // 加载更多发布内容
    loadMorePosts() {
        console.log('=== 加载更多发布内容 ===');
        if (this.data.postsHasMore) {
            this.fetchPublishedList(true);
        }
    },

    // 发布内容卡片点击事件
    onPostCardClick(e: any) {
        const item = e.currentTarget.dataset.item;
        console.log('点击发布内容卡片:', item);
        
        if (item && item.id) {
            // 跳转到详情页面
            wx.navigateTo({
                url: `/pages/inspection/detail/detail?id=${item.id}&uid=${item.uid}&author_id=${item.username}`
            });
        } else {
            wx.showToast({
                title: '数据错误',
                icon: 'error'
            });
        }
    },

    // 点赞内容卡片点击事件
    onLikeCardClick(e: any) {
        const item = e.currentTarget.dataset.item;
        console.log('点击点赞内容卡片:', item);
        
        if (item && item.id) {
            // 跳转到详情页面
            wx.navigateTo({
                url: `/pages/inspection/detail/detail?id=${item.id}&uid=${item.uid}&author_id=${item.username}`
            });
        } else {
            wx.showToast({
                title: '数据错误',
                icon: 'error'
            });
        }
    },
    
    // ========== 标签管理相关方法 ==========
    
    // 获取可用标签列表
    async fetchAvailableTags() {
        try {
            console.log('=== 获取标签列表 ===');
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            if (!uid) {
                console.error('用户uid不存在，无法获取标签列表');
                return;
            }
            
            const res = await api.getAvailableTags({ uid });
            console.log('标签列表接口返回:', res);
            
            if (res && res.tags && Array.isArray(res.tags)) {
                const tagsWithSelection = res.tags.map(tag => ({
                    name: tag,
                    selected: false
                }));
                this.setData({
                    availableTags: tagsWithSelection
                });
                console.log('标签列表设置完成:', tagsWithSelection);
            } else {
                console.log('标签列表为空');
                this.setData({
                    availableTags: []
                });
            }
        } catch (error) {
            console.error('获取标签列表失败:', error);
            this.setData({
                availableTags: []
            });
        }
    },
    
    // 显示标签管理弹窗
    showTagManager() {
        this.setData({
            showTagModal: true
        });
    },
    
    // 隐藏标签管理弹窗
    hideTagManager() {
        this.setData({
            showTagModal: false,
            newTagName: ''
        });
    },
    
    // 标签名称输入
    onTagNameInput(e: any) {
        this.setData({
            newTagName: e.detail.value
        });
    },
    
    // 创建新标签
    async onCreateTag() {
        const tagName = this.data.newTagName.trim();
        
        if (!tagName) {
            wx.showToast({
                title: '请输入标签名称',
                icon: 'none'
            });
            return;
        }
        
        // 检查标签是否已存在
        if (this.data.availableTags.some(tag => tag.name === tagName)) {
            wx.showToast({
                title: '标签已存在',
                icon: 'none'
            });
            return;
        }
        
        try {
            console.log('=== 创建新标签 ===');
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            if (!uid) {
                wx.showToast({
                    title: '用户信息错误',
                    icon: 'error'
                });
                return;
            }
            
            const res = await api.createTag({ action: 'add', uid: uid, tags: tagName });
            console.log('创建标签接口返回:', res);
            
            if (res && (res as any).status === 'success') {
                // 创建成功，重新获取标签列表确保数据一致性
                await this.fetchAvailableTags();
                
                this.setData({
                    newTagName: '',
                    showTagModal: false // 关闭弹窗
                });
                
                wx.showToast({
                    title: '标签创建成功',
                    icon: 'success'
                });
            } else {
                wx.showToast({
                    title: (res as any)?.message || '创建失败',
                    icon: 'error'
                });
            }
        } catch (error) {
            console.error('创建标签失败:', error);
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'error'
            });
        }
    },
    
    // 删除标签
    async onDeleteTag(e: any) {
        const tagName = e.currentTarget.dataset.tag;
        if (!tagName) return;
        
        wx.showModal({
            title: '确认删除',
            content: `确定要删除标签"${tagName}"吗？`,
            success: async (res) => {
                if (res.confirm) {
                    try {
                        console.log('=== 删除标签 ===');
                        const userInfo = common.getAppUserInfo();
                        const uid = userInfo?.uid || userInfo?.userId;
                        
                        if (!uid) {
                            wx.showToast({
                                title: '用户信息错误',
                                icon: 'error'
                            });
                            return;
                        }
                        
                        const deleteRes = await api.deleteTag({ action: 'delete', uid: uid, tags: tagName });
                        console.log('删除标签接口返回:', deleteRes);
                        
                        if (deleteRes && (deleteRes as any).status === 'success') {
                            // 删除成功，更新本地标签列表
                            const newTags = this.data.availableTags.filter(tag => tag.name !== tagName);
                            this.setData({
                                availableTags: newTags
                            });
                            
                            // 重新获取标签列表和收藏列表，确保数据同步
                            console.log('标签删除成功，重新获取标签列表和收藏列表');
                            await this.fetchAvailableTags(); // 重新获取标签列表
                            await this.fetchCollections(); // 重新获取收藏列表
                            
                            wx.showToast({
                                title: '标签删除成功',
                                icon: 'success'
                            });
                        } else {
                            wx.showToast({
                                title: (deleteRes as any)?.message || '删除失败',
                                icon: 'error'
                            });
                        }
                    } catch (error) {
                        console.error('删除标签失败:', error);
                        wx.showToast({
                            title: '网络错误，请重试',
                            icon: 'error'
                        });
                    }
                }
            }
        });
    },
    
    // 标签点击事件（切换选中状态）
    async onTagClick(e: any) {
        const tagName = e.currentTarget.dataset.tag;
        const index = e.currentTarget.dataset.index;
        console.log('点击标签:', tagName, 'index:', index);
        
        // 更新标签选中状态
        const availableTags = [...this.data.availableTags];
        availableTags[index].selected = !availableTags[index].selected;
        
        // 更新选中标签列表
        const selectedTags = availableTags.filter(tag => tag.selected).map(tag => tag.name);
        
        this.setData({
            availableTags: availableTags,
            selectedTags: selectedTags
        });
        
        console.log('当前选中的标签:', selectedTags);
        
        // 根据当前tab筛选内容
        if (this.data.activeTab === 'collections') {
            await this.filterCollectionsByTags(selectedTags);
        } else if (this.data.activeTab === 'posts') {
            await this.filterPostsByTags(selectedTags);
        }
    },
    
    // 根据标签筛选发布内容
    async filterPostsByTags(selectedTags: string[]) {
        try {
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            if (!uid) {
                console.error('用户uid不存在，无法筛选发布内容');
                return;
            }
            
            if (selectedTags.length === 0) {
                // 如果没有选中标签，显示所有发布内容
                this.setData({
                    filteredPosts: this.data.posts
                });
                return;
            }
            
            console.log('=== 根据标签筛选发布内容 ===');
            console.log('选中的标签:', selectedTags);
            
            const res = await api.searchByTags({
                uid: uid,
                tags: selectedTags,
                type: 'publish',
                page_index: 1,
                page_size: 20
            });
            
            console.log('发布内容标签筛选接口返回:', res);
            
            if (res && res.data && Array.isArray(res.data)) {
                const filteredPosts = res.data.map((item: any) => ({
                    ...item,
                    icon: this.getFileIcon(item.title || item.ai_title || '')
                }));
                
                this.setData({
                    filteredPosts: filteredPosts
                });
                
                console.log('筛选后的发布内容:', filteredPosts);
            } else {
                this.setData({
                    filteredPosts: []
                });
            }
        } catch (error) {
            console.error('筛选发布内容失败:', error);
            this.setData({
                filteredPosts: []
            });
        }
    },
    
    // 清空已选标签
    async clearSelectedTags() {
        this.setData({
            selectedTags: []
        });
        console.log('已清空所有选中的标签');
        
        // 清空标签后，重新获取收藏列表
        await this.fetchCollections();
    },
    
    // ========== 标签筛选相关方法 ==========
    
    // 根据标签筛选收藏内容
    async filterCollectionsByTags(selectedTags: string[]) {
        try {
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            if (!uid) {
                console.error('用户uid不存在，无法筛选内容');
                return;
            }
            
            if (selectedTags.length === 0) {
                // 如果没有选中标签，获取所有收藏内容
                await this.fetchCollections();
                return;
            }
            
            console.log('=== 根据标签筛选内容 ===');
            console.log('选中的标签:', selectedTags);
            
            const res = await api.searchByTags({
                uid: uid,
                tags: selectedTags,
                type: 'collection',
                page_index: 1,
                page_size: 20
            });
            
            console.log('标签筛选接口返回:', res);
            
            if (res && res.data && Array.isArray(res.data)) {
                // 处理数据格式，确保与原有收藏列表格式一致
                const processedCollections = res.data.map((item: any) => ({
                    id: item.id,
                    uid: item.uid,
                    title: item.title || item.ai_title,
                    ai_title: item.ai_title,
                    content: item.content,
                    citation: item.citation,
                    link: item.link,
                    image_url: item.image_url,
                    collection: item.collection_num || item.collection || 0,
                    like: item.like_num || item.like || 0,
                    comments: item.comments_count || item.comments || 0,
                    username: item.username,
                    avatar: item.avatar,
                    tags: item.tag || [],
                    publish_time: item.publish_time,
                    createTime: item.createTime,
                    checked: false,
                    collected: true // 筛选出的都是收藏内容
                }));
                
                this.setData({
                    collections: processedCollections,
                    filteredCollections: processedCollections
                });
                
                console.log('标签筛选结果设置完成:', processedCollections);
            } else {
                console.log('标签筛选结果为空');
                this.setData({
                    collections: [],
                    filteredCollections: []
                });
            }
        } catch (error) {
            console.error('根据标签筛选内容失败:', error);
            // 筛选失败时，显示所有收藏内容
            await this.fetchCollections();
        }
    },
    
    // 显示标签Action Sheet
    showTagActionSheet() {
        this.setData({
            showTagActionSheet: true
        });
    },
    
    // 隐藏标签Action Sheet
    hideTagActionSheet() {
        this.setData({
            showTagActionSheet: false,
            showTagSettingsMenu: false
        });
    },
    
    // 显示/隐藏标签设置菜单
    toggleTagSettingsMenu() {
        this.setData({
            showTagSettingsMenu: !this.data.showTagSettingsMenu
        });
    },
    
    // ========== 重命名标签相关方法 ==========
    
    // 显示重命名弹窗
    onRenameTag(e: any) {
        const tagName = e.currentTarget.dataset.tag;
        this.setData({
            showRenameModal: true,
            renameTagName: tagName,
            renameNewName: tagName // 默认填入原标签名
        });
    },
    
    // 隐藏重命名弹窗
    hideRenameModal() {
        this.setData({
            showRenameModal: false,
            renameTagName: '',
            renameNewName: ''
        });
    },
    
    // 重命名输入
    onRenameInput(e: any) {
        this.setData({
            renameNewName: e.detail.value
        });
    },
    
    // 确认重命名
    async onConfirmRename() {
        const oldTag = this.data.renameTagName;
        const newTag = this.data.renameNewName.trim();
        
        if (!newTag) {
            wx.showToast({
                title: '请输入新标签名称',
                icon: 'none'
            });
            return;
        }
        
        if (newTag === oldTag) {
            wx.showToast({
                title: '新标签名与原标签名相同',
                icon: 'none'
            });
            return;
        }
        
        // 检查新标签名是否已存在
        if (this.data.availableTags.includes(newTag)) {
            wx.showToast({
                title: '标签名已存在',
                icon: 'none'
            });
            return;
        }
        
        try {
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            if (!uid) {
                wx.showToast({
                    title: '用户信息错误',
                    icon: 'error'
                });
                return;
            }
            
            const res = await api.renameTag({ 
                action: 'rename', 
                uid: uid, 
                old_tag: oldTag, 
                new_tag: newTag 
            });
            
            if (res && (res as any).status === 'success') {
                // 重命名成功，更新本地标签列表
                const newTags = this.data.availableTags.map(tag => 
                    tag.name === oldTag ? { ...tag, name: newTag } : tag
                );
                
                // 更新选中标签列表
                const newSelectedTags = this.data.selectedTags.map(tag => 
                    tag === oldTag ? newTag : tag
                );
                
                this.setData({
                    availableTags: newTags,
                    selectedTags: newSelectedTags,
                    showRenameModal: false,
                    renameTagName: '',
                    renameNewName: ''
                });
                
                // 重新获取标签列表和收藏列表，确保数据同步
                console.log('标签重命名成功，重新获取标签列表和收藏列表');
                await this.fetchAvailableTags(); // 重新获取标签列表
                await this.fetchCollections(); // 重新获取收藏列表
                
                wx.showToast({
                    title: '重命名成功',
                    icon: 'success'
                });
            } else {
                wx.showToast({
                    title: (res as any)?.message || '重命名失败',
                    icon: 'error'
                });
            }
        } catch (error) {
            console.error('重命名标签失败:', error);
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'error'
            });
        }
    },

    // 删除选中的标签
    async deleteSelectedTags() {
        if (this.data.selectedTags.length === 0) {
            wx.showToast({
                title: '请先选择要删除的标签',
                icon: 'none'
            });
            return;
        }
        
        const tagsToDelete = this.data.selectedTags.join('、');
        wx.showModal({
            title: '确认删除',
            content: `确定要删除标签"${tagsToDelete}"吗？`,
            success: async (res) => {
                if (res.confirm) {
                    try {
                        console.log('=== 批量删除标签 ===');
                        const userInfo = common.getAppUserInfo();
                        const uid = userInfo?.uid || userInfo?.userId;
                        
                        if (!uid) {
                            wx.showToast({
                                title: '用户信息错误',
                                icon: 'error'
                            });
                            return;
                        }
                        
                        // 逐个删除选中的标签
                        for (const tagName of this.data.selectedTags) {
                            const deleteRes = await api.deleteTag({ 
                                action: 'delete', 
                                uid: uid, 
                                tags: tagName 
                            });
                            console.log(`删除标签${tagName}接口返回:`, deleteRes);
                            
                            if (!deleteRes || (deleteRes as any).status !== 'success') {
                                wx.showToast({
                                    title: `删除标签"${tagName}"失败`,
                                    icon: 'error'
                                });
                                return;
                            }
                        }
                        
                        // 删除成功，更新本地标签列表
                        const newTags = this.data.availableTags.filter(tag => !this.data.selectedTags.includes(tag.name));
                        this.setData({
                            availableTags: newTags,
                            selectedTags: []
                        });
                        
                        wx.showToast({
                            title: '标签删除成功',
                            icon: 'success'
                        });
                        
                    } catch (error) {
                        console.error('删除标签失败:', error);
                        wx.showToast({
                            title: '网络错误，请重试',
                            icon: 'error'
                        });
                    }
                }
            }
        });
    },

    // 重命名选中的标签
    renameSelectedTag() {
        if (this.data.selectedTags.length === 0) {
            wx.showToast({
                title: '请先选择要重命名的标签',
                icon: 'none'
            });
            return;
        }
        
        if (this.data.selectedTags.length > 1) {
            wx.showToast({
                title: '只能选择一个标签进行重命名',
                icon: 'none'
            });
            return;
        }

        const tagToRename = this.data.selectedTags[0];
        this.setData({
            showRenameModal: true,
            renameTagName: tagToRename,
            renameNewName: ''
        });
    },

    // Action Sheet中的标签点击事件
    async onActionSheetTagClick(e: any) {
        const tagName = e.currentTarget.dataset.tag;
        const index = e.currentTarget.dataset.index;
        
        // 如果有当前选中的内容，则添加标签到该内容
        if (this.data.currentItem) {
            await this.addTagToInspiration(this.data.currentItem.id, tagName);
            this.setData({
                showTagActionSheet: false,
                currentItem: null
            });
            return;
        }
        
        // 更新标签选中状态
        const availableTags = [...this.data.availableTags];
        availableTags[index].selected = !availableTags[index].selected;
        
        // 更新选中标签列表
        const selectedTags = availableTags.filter(tag => tag.selected).map(tag => tag.name);
        
        this.setData({
            availableTags: availableTags,
            selectedTags: selectedTags
        });
        
        // 根据选中标签筛选内容
        await this.filterCollectionsByTags(selectedTags);
    },

    // 为内容添加标签
    async onAddTagToItem(e: any) {
        const item = e.currentTarget.dataset.item;
        console.log('为内容添加标签:', item);
        
        // 显示标签选择弹窗
        this.setData({
            showTagActionSheet: true,
            currentItem: item
        });
    },

    // 给用户增加新标签
    async addTagToUser(tagName: string) {
        try {
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            if (!uid) {
                wx.showToast({
                    title: '用户信息错误',
                    icon: 'error'
                });
                return;
            }

            const res = await api.createTag({ action: 'add', uid: uid, tags: tagName });
            console.log('给用户增加标签接口返回:', res);
            
            if (res && (res as any).status === 'success') {
                await this.fetchAvailableTags();
                wx.showToast({
                    title: '标签添加成功',
                    icon: 'success'
                });
            } else {
                wx.showToast({
                    title: (res as any)?.message || '添加失败',
                    icon: 'error'
                });
            }
        } catch (error) {
            console.error('添加用户标签失败:', error);
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'error'
            });
        }
    },

    // 给灵感添加标签
    async addTagToInspiration(inspirationId: string, tagName: string) {
        try {
            const userInfo = common.getAppUserInfo();
            const uid = userInfo?.uid || userInfo?.userId;
            
            const res = await api.addTagToInspiration({ 
                action: 'add',
                id: inspirationId, 
                uid: uid,
                tags: tagName 
            });
            console.log('给灵感添加标签接口返回:', res);
            
            if (res && (res as any).status === 'success') {
                // 刷新当前数据
                if (this.data.activeTab === 'collections') {
                    await this.fetchCollections();
                } else if (this.data.activeTab === 'posts') {
                    await this.fetchPublishedList();
                }
                
                wx.showToast({
                    title: '标签添加成功',
                    icon: 'success'
                });
            } else {
                wx.showToast({
                    title: (res as any)?.message || '添加失败',
                    icon: 'error'
                });
            }
        } catch (error) {
            console.error('添加灵感标签失败:', error);
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'error'
            });
        }
    }
});